package com.ilop.sthome.common.udp;

import android.util.Log;

import com.ilop.sthome.data.bean.GatewayBean;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * @author skygge
 * @date 2020-03-17.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：udp接收内网数据
 */
public class UdpReceiveHelper implements Runnable{
    private static final String TAG = UdpReceiveHelper.class.getSimpleName();

    private DatagramSocket datagramSocket;
    private DatagramPacket datagramPacket;
    private boolean mDestructionUdp = true;

    private static final String ACK = "NODE_ACK";//设备应答
    private static final String SEND = "NODE_SEND";//设备上报

    private static final String CMD_ACTION = "action";
    private static final String CMD_DEVICE_ID = "devID";
    private static final String CMD_MSG = "msg";
    private static final String CMD_CODE = "CMD_CODE";

    private OnUdpReceiveCallBack mCallBack;
    private String mUdpMessage;
    private String mIpAddress;

    UdpReceiveHelper(DatagramSocket socket, DatagramPacket packet){
        this.datagramSocket = socket;
        this.datagramPacket = packet;
    }

    public void setCallBack(OnUdpReceiveCallBack mCallBack) {
        this.mCallBack = mCallBack;
    }

    @Override
    public void run() {
        while (mDestructionUdp){
            try {
                datagramSocket.receive(datagramPacket);
                String msg = new String(datagramPacket.getData());
                mIpAddress = datagramPacket.getAddress().toString();
                mIpAddress = mIpAddress.substring(mIpAddress.lastIndexOf("/") + 1 );
                String json = msg.substring(0, msg.lastIndexOf("}}") + 2);
                Log.i(TAG,"receiveData:" + json);
                receiveData(json);
            } catch (IOException | NullPointerException e) {
                close();
                Log.e(TAG, "receive error " + e.getLocalizedMessage());
            }
        }
    }

    /**
     * 解析UDP数据
     */
    private void receiveData(String msg){
        try {
            JSONObject jsonObject = new JSONObject(msg);
            if(jsonObject.has(CMD_ACTION) && jsonObject.has(CMD_MSG)) {
                JSONObject jsonMsg = jsonObject.getJSONObject(CMD_MSG);
                String deviceName = jsonObject.getString(CMD_DEVICE_ID);
                int command = jsonMsg.has(CMD_CODE) ? jsonMsg.getInt(CMD_CODE) : -1;
                if(0 == command){// NODE_ACK ip地址中的网关
                    boolean isSearchOver = ControllerUdpHelper.getInstance().mUdpSearchFinish; //udp激活后再显示在线
                    GatewayBean gateway = new GatewayBean();
                    gateway.setName(deviceName);
                    gateway.setIpAddress(mIpAddress);
                    gateway.setOnline(isSearchOver);
                    GatewayUdpUtil.getInstance().insertGateway(gateway);
                }else{
                    if(GatewayUdpUtil.getInstance().checkUdpDeviceBelongToUser(deviceName)){
                        GatewayUdpUtil.getInstance().setReceiveDataOrNot(deviceName, command);
                        if (!msg.equals(mUdpMessage)) {
                            if (mCallBack!=null){
                                mCallBack.receiveData(deviceName, msg);
                                mCallBack.receiveAnswer(deviceName);
                                mUdpMessage = msg;
                            }
                        }
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            ControllerUdpHelper.getInstance().unRegisterUdpReceiveCallBack();
        }
    }

    void close(){
        try {
            mDestructionUdp = false;
            mCallBack = null;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
